<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-button type="primary" @click="showAdddialog">添加分类</el-button>
      <!-- 商品列表展示区域 -->
      <tree-table
        style="width: 100%; margin-top: 15px"
        :data="categories"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- 是否有效列 -->
        <template slot="isok" slot-scope="scope">
          <i
            v-if="scope.row.cat_deleted == false"
            class="el-icon-success"
            style="color: lightgreen"
          ></i>
          <i v-else class="el-icon-error"></i>
        </template>
        <!-- 排序列表 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level == 1" type="success"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作列 -->
        <template slot="option" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            @click="editcategories(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            @click="removecategories(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页列表 -->
      <div class="block">
        <span class="demonstration">完整功能</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="categoriesinfo.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="categoriesinfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totle"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加对话框弹框 -->
    <el-dialog
      title="编辑信息"
      :visible.sync="editVisible"
      width="50%"
      @close="closed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="ruleForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options 用来指定数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader
            v-model="selectKeys"
            :options="parentCatelist"
            :props="caseProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCat">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //商品分类数据
      categories: [],
      //获取数据传的参数
      categoriesinfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //   数据总数
      totle: 0,
      //为table指定列的定义
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        { label: '是否有效', type: 'template', template: 'isok' },
        { label: '排序', type: 'template', template: 'order' },
        { label: '操作', type: 'template', template: 'option' },
      ],
      //添加弹框的显示与隐藏
      editVisible: false,
      // 添加用户的表单数据
      ruleForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0,
      },
      // 父级分类列表数据
      parentCatelist: [],
      //指定级联选择器的配置对象
      caseProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
      },
      //选中的父级id分类数组
      selectKeys: [],
      // 判断是添加还是编辑
      addoredit: '',
      // 点击按钮获取到的当前cat_id
      editID: 0,
      // 添加表单的验证规则对象
      rules: {
        cat_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  mounted() {
    this.getcategorieslist()
  },
  methods: {
    //获取商品信息
    async getcategorieslist() {
      const { data: res } = await this.$http.get('categories', {
        params: this.categoriesinfo,
      })
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.categories = res.data.result
      this.totle = res.data.total
    },
    handleSizeChange(newSize) {
      this.categoriesinfo.pagesize = newSize
      this.getcategorieslist()
    },
    handleCurrentChange(newpage) {
      this.categoriesinfo.pagenum = newpage
      this.getcategorieslist()
    },
    // 显示添加弹框
    showAdddialog() {
      this.getParentcatdialog()
      this.editVisible = true
      // 为true说明是添加数据
      this.addoredit = true
    },
    // 获取添加下拉列表的数据
    async getParentcatdialog() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败！')
      this.parentCatelist = res.data
    },
    // 下拉选择项发生改变时触发
    handleChange() {
      // console.log(this.selectKeys)
      // 如果selectKeys数组的length大于0，说明选中的父级分类，反之没有选中
      if (this.selectKeys.length > 0) {
        this.ruleForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        this.ruleForm.cat_level = this.selectKeys.length
        return
      } else {
        this.ruleForm.cat_pid = this.ruleForm.cat_level = 0
      }
    },
    // 添加新用户
    addCat() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        if (this.addoredit) {
          const { data: res } = await this.$http.post(
            'categories',
            this.ruleForm
          )
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          this.$message.success('添加成功！')
          this.getcategorieslist()
          this.selectKeys = []
          this.ruleForm.cat_name = ''
        } else {
          const { data: res } = await this.$http.put(
            'categories/' + this.editID,
            { cat_name: this.ruleForm.cat_name }
          )
          if (res.meta.status !== 200) return this.$message.error('更新失败')
          this.$message.success('更新数据成功')
          this.getcategorieslist()
        }
        this.editVisible = false
      })
    },
    // 监听添加用户对话框的关闭事件
    closed() {
      // resetFields对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.ruleForm.resetFields()
    },
    //获取编辑弹框数据
    async editcategories(id) {
      this.editID = id
      // 为false说明是编辑数据
      this.addoredit = false
      this.editVisible = true
      this.getParentcatdialog()
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      // console.log(res.data)
      this.ruleForm = res.data
    },
    // 删除商品信息
    async removecategories(id) {
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除数据成功')
      this.getcategorieslist()
    },
  },
}
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>